import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import type { RequestConfig, ResponseData } from './types'
export type { RequestConfig, ResponseData } from './types'

export class Request {
  private instance: AxiosInstance

  constructor(config: RequestConfig = {}) {
    this.instance = axios.create({
      timeout: 5000,
      ...config
    })

    this.setupInterceptors()
  }

  private setupInterceptors() {
    this.instance.interceptors.response.use(
      response => response.data,
      error => Promise.reject(error)
    )
  }

  async get<T>(url: string, data = {}, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    config = {
      ...config,
      params: data
    }
    return this.instance.get(url, config)
  }

  async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.post(url, data, config)
  }

  async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    return this.instance.put(url, data, config)
  }

  async delete<T>(url: string, data = {}, config?: AxiosRequestConfig): Promise<ResponseData<T>> {
    config = {
      ...config,
      params: data
    }
    return this.instance.delete(url, config)
  }
}

export default new Request({
  baseURL: 'https://open.feishu.cn/open-apis',
  timeout: 5000
})